package com.tianhua.javs.core.func.translate.varassign;

import com.tianhua.javs.client.bean.JavsSegmentBean;
import com.tianhua.javs.client.func.ITranslatorFunc;
import com.tianhua.javs.client.model.FieldModel;
import com.tianhua.javs.core.annotations.Segment;
import com.tianhua.javs.core.constant.TagConstants;
import com.tianhua.javs.core.func.translate.AbstractTranslator;
import org.springframework.stereotype.Component;


/**
 * Description:
 * date: 2022/2/12
 *
 * @author shenshuai
 * @version 1.0.0
 * @since JDK 1.8
 */
@Component(value = "autowiredFunc")
@Segment(tag = "autowired",scriptFuncBean = "springBeanAssignFunc")
public class AutowiredFunc extends AbstractTranslator implements ITranslatorFunc {
    @Override
    public JavsSegmentBean translate(String shellSegment) {
        FieldModel fieldModel = buildFieldModel(shellSegment,"autowired");
        if(fieldModel == null){
            //未匹配
            return JavsSegmentBean.getInstance(shellSegment);
        }
        return JavsSegmentBean.getMatchInstance(fieldModel);
    }


    /**
     * 基于半原生代码构建全局属性信息
     * @param javaCode
     * @return
     */
    private FieldModel buildFieldModel(String javaCode,String tag){
        String [] javaCodeArr = javaCode.split("=");
        String [] javaVarTypeArr = javaCodeArr[1].split("\\.");

        if(!javaVarTypeArr[1].trim().equals(tag)){
            return null;
        }

        FieldModel fieldModel = new FieldModel();
        fieldModel.setAnnotation("@Autowired");

        fieldModel.setClassName(javaVarTypeArr[0]);

        String [] leftSegmentArr = javaCodeArr[0].split(" ");
        if(leftSegmentArr.length == 1){
            javaCodeArr[0] = TagConstants.PRIVATE + " " +javaCodeArr[0];
        }
        leftSegmentArr = javaCodeArr[0].split(" ");

        fieldModel.setFieldSimpleName(leftSegmentArr[leftSegmentArr.length - 1]);
        if(javaCodeArr[0].trim().startsWith(TagConstants.PUBLIC)){
            fieldModel.setVisibility(TagConstants.PUBLIC);
        }else if(javaCodeArr[0].trim().startsWith(TagConstants.PRIVATE)) {
            fieldModel.setVisibility(TagConstants.PRIVATE);
        }else {
            fieldModel.setVisibility(TagConstants.PROTECTED);
        }
        return fieldModel;
    }

}
